package com.gatewaydy.web;

import com.gatewaydy.gatwayhandler.GatewayServiceHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.FilterDefinition;
import org.springframework.cloud.gateway.handler.predicate.PredicateDefinition;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.cloud.gateway.support.NameUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: LCG
 * @date: 2022-10-27 11:32:40
 * @description: 测试gateway的持久化，从数据库加载持久化信息
 **/
@RestController
public class GatewayController {

    @Autowired
    private GatewayServiceHandler gatewayServiceHandler;

    /**
     * @author: LCG
     * @date: 2022-10-27 13:24:36
     * @description:  测试添加一个路由信息 下边的服务信息对应的服务是 cloud-server2 中的代码
     */
    @RequestMapping("addRoutes")
    public String addRoutesTest() throws URISyntaxException {

        RouteDefinition routeDefinition=new RouteDefinition();
        routeDefinition.setId("grpc-server2");
        routeDefinition.setUri(new URI("lb://grpc-server2"));

        /**设置predicates**/
        List<PredicateDefinition> predicates=new ArrayList<>();
        PredicateDefinition predicateDefinition=new PredicateDefinition();
        //Path 后的内容可以是多个路径，多个路径用逗号隔开
        predicateDefinition.setName("Path");
        //源代码中就是这么定义的在PredicateDefinition类中的低35行代码
        String generateName = NameUtils.generateName(0);
        Map<String,String> args=new HashMap<>();
        //设置路由路径
        args.put(generateName,"/api/server2/**");
        predicateDefinition.setArgs(args);
        predicates.add(predicateDefinition);
        routeDefinition.setPredicates(predicates);

        //设置filters
        List<FilterDefinition> filters=new ArrayList<>();
        FilterDefinition filterDefinition=new FilterDefinition();
        filterDefinition.setName("StripPrefix");

        Map<String,String> argsFilter=new HashMap<>(20);
        String generateFilterKey = NameUtils.generateName(0);
        argsFilter.put(generateFilterKey,"2");
        filterDefinition.setArgs(argsFilter);

        filters.add(filterDefinition);

        routeDefinition.setFilters(filters);

        return gatewayServiceHandler.addRoutes(routeDefinition);

    }

    @RequestMapping("addRoutes2")
    public String addRoutesTest2(@RequestBody RouteDefinition routeDefinition) throws URISyntaxException {

        return gatewayServiceHandler.addRoutes(routeDefinition);

    }


    @RequestMapping("deleteRoutes")
    public String deleteRoutes(){

       return  gatewayServiceHandler.deleteRoute("grpc-server2","g1");
    }




}
